import pathlib
import time
import re
import typing
import os
import json
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
import playsound
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *





if __name__ == "__main__":
    # 切换工作目录到当前脚本所在目录
    os.chdir(pathlib.Path(__file__).parent.absolute().resolve().__str__())
    Modify_Time = "2025年7月28日17:25:52"
    print(f"当前【拼多多】自动化脚本的版本日期是 : 【{Modify_Time}】")
    
    
    # 判断是否是否启动浏览器
    from Wrapper.Pdd.Initialization import * 
    CheckResul_Process = Checkout_Has_Msedge_Process()  # 检测是否有 msedge.exe 进程
    if(CheckResul_Process == False):
        Start_Debugmode_Browser()
    else:
        CheckResul_DebugModu = Checkout_Debug_Mode_Activate()   # 检测是否处于调试模式
        if(CheckResul_DebugModu == False):
            _select_execute = Custom_Message(text="当前不是调试环境\n请问是否需要关闭所有 msedge.exe 进程\n重新打开!",type=1)
            # 1.判断选择那种方式启动浏览器
            match _select_execute:
                case 1:
                    Close_All_Msedge_Process()
                    Start_Debugmode_Browser()
                case 2:
                    exit(0)
                case _:
                    exit(0)
        
    
    # # 基础配置
    driver = Fast_Create_WebDriver_Wait_Action()
    Goto_CurrentActivateUrl(driver)
    # ConfigData = yaml.safe_load(stream=open(file="./config.yaml",mode="r",encoding="utf-8"))['PDD']
    ConfigData = json.load(fp=open(file="./config.json",mode="r",encoding="utf-8"))['PDD']


    # 选择类目
    from Wrapper.Pdd.OpenUrl import *
    from Wrapper.Pdd.Select_Category import *
    Goto_Select_Category(driver)
    On_SelectPage_Select_FirstCategory(driver,ConfigData['FirstCategory'])
    On_SelectPage_Select_SecondCategory(driver,ConfigData['SecondCategory'])
    Goto_Parameter_Input(driver)



    from Wrapper.Pdd.Directory import *
    from Wrapper.Pdd.UploadMainImage import *
    MainImageDirectory = GetExistsDirectory(ConfigData['MainDirectoryFilterList'])
    if MainImageDirectory:
        On_InputPage_UploadMainPicture_ByDirectory(driver,picture_directory_path=MainImageDirectory)




    # # 填写参数
    from Wrapper.Pdd.Input_Parameters import *
    for AttributeName,AttributeValue in ConfigData['TBBasicParameters'].items():
        On_InputPage_InputBasicParameters(driver,AttributeName,AttributeValue)




    # 上传详情图
    from Wrapper.Pdd.UploadDetailImage import *
    DetailImageDirectory = GetExistsDirectory(ConfigData['DetailDirectoryFilterList'])
    if DetailImageDirectory:    
        On_InputPage_UploadDetail_Picture_ByDirectory(driver=driver,picture_directory_path=DetailImageDirectory)




    # 上传视频
    from Wrapper.Pdd.UploadMainVideo import *
    MainVideoDirectory = GetExistsDirectory(ConfigData['MainVideoDirectoryFilterList'])
    if MainVideoDirectory:
        On_InputPage_UploadMain_Video_ByDirectory(driver=driver,video_directory_path=MainVideoDirectory)
    



    # 填写 Sku
    from Wrapper.Pdd.Input_Sku import *
    SkuImageDirectory = GetExistsDirectory(ConfigData['SkuImageDirectoryFilterList'])
    for root,dirs,files in os.walk(SkuImageDirectory):
        for file in files:
            if file.endswith(".jpeg") or file.endswith(".jpg") or file.endswith(".png"):
                skuimagepath = pathlib.Path(os.path.join(root, file)).absolute().resolve()
                basename = pathlib.Path(os.path.join(root, file)).absolute().resolve().stem
                colorname = re.sub(r'[^\u4e00-\u9fff]', '', basename)
                
                On_InputPage_UploadSkuPicture_And_SetSkuName(driver,colorname,skuimagepath)




    # 填写码数
    from Wrapper.Pdd.Input_SizeParms import *
    On_InputPage_SelectSizeType(driver,ConfigData['ChartSizeType'])
    for sizechar in ConfigData['ChartSizeList']:
        On_InputPage_SelectSizeChart(driver=driver,size_chart_name=sizechar)




    # 停用尺码表
    On_InputPage_StopDefaultSizeChart(driver)



    from Wrapper.Pdd.Input_Price_Code import *
    On_InputPage_Input_Batch_Price_And_Code(driver,ConfigData['Number'],ConfigData['Price'],ConfigData['Code'])



    from Wrapper.Pdd.Input_Logistics import *
    On_InputPage_InputLogistics_Day(driver=driver,day=ConfigData['InputLogistics_Day'])
    # from Wrapper.Pdd.Input_Other_Params import *
    On_InputPage_InputLogistics_Template(driver=driver,template_name="新疆西藏不配送默认模板")
    


    from Wrapper.Pdd.Basic import *
    On_HtmlPageScroll_To_Top(driver)




    # 搜索同款
    from Wrapper.Pdd.Find_Same import *
    Find_MainImageTitle(driver=driver,Picture_Path=pathlib.Path(MainImageDirectory).iterdir().__next__().absolute().resolve())




    # 播放声音
    playsound.playsound(sound=pathlib.Path("./Resource/PinduoduoSound.mp3").absolute())



    # 结束程序
    driver.quit()
    